<template>

    <div id="panorama-container" ref="panoramaContainer" @dblclick="handleDoubleClick">
        <!-- 坐标显示面板 -->
        <div v-if="clickPosition" class="position-panel">
            视角坐标：Yaw: {{ clickPosition.yaw.toFixed(2) }}°,
            Pitch: {{ clickPosition.pitch.toFixed(2) }}°
        </div>
        <!-- 增强型标记点弹窗 -->
        <div v-if="activeHotspot" class="hotspot-modal" @click.self="closeModal">
            <div class="modal-content">
                <button class="close-btn" @click="closeModal">×</button>
                <h3>{{ activeHotspot.title }}</h3>

                <!-- 视频播放器 -->
                <video
                        v-if="activeHotspot.video"
                        controls
                        :poster="activeHotspot.poster"
                        class="hotspot-video">
                    <source :src="activeHotspot.video" type="video/mp4">
                </video>

                <!-- 富文本内容 -->
                <div class="hotspot-description" v-html="activeHotspot.description"></div>

                <!-- 附加图片 -->
                <div class="image-gallery" v-if="activeHotspot.images">
                    <img
                            v-for="(img, index) in activeHotspot.images"
                            :key="index"
                            :src="img"
                            @click="openLightbox(index)">
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import 'pannellum/src/css/pannellum.css';
    import 'pannellum/src/js/libpannellum';
    import 'pannellum/src/js/pannellum';
    import {EventBus} from "../../utils/event-bus";

    export default {
        name: 'PanoramaViewer',
        inject: ['imgUrl'], // 注入公共变量
        props: {
            currentRoom: String,
        },
        data() {
            return {
                activeHotspot: null,
                clickPosition: null,
                viewer: null,
                hotspots:null,
                activeTooltip: null,
                tooltipPosition: {
                    left: '0px',
                    top: '0px'
                },
                scenes: {
                    // 'living-room': {
                    //     title: '北湖节点01',
                    //     // panorama: require('@/assets/img/living-room.jpg'),
                    //     panorama: this.imgUrl+'IMG_20250106_085136_00_005.jpg', // 使用绝对路径
                    //     preview: this.imgUrl+'IMG_20250106_085136_00_005sl.jpg', // 使用绝对路径
                    //     hotSpots: []
                    // },
                    // 'bedroom1': {
                    //     title: '观赏草原',
                    //     // panorama: require('@/assets/img/bedroom1.jpg'),
                    //     panorama: this.imgUrl+'IMG_20250106_085352_00_007.jpg', // 使用绝对路径
                    //     preview: this.imgUrl+'IMG_20250106_085352_00_007sl.jpg', // 使用绝对路径
                    //     hotSpots: []
                    // },
                    // 'bedroom2': {
                    //     title: '北湖节点02',
                    //     // panorama: require('@/assets/img/bedroom2.jpg'),
                    //     panorama: this.imgUrl+'IMG_20250106_085924_00_011.jpg', // 使用绝对路径
                    //     preview: this.imgUrl+'IMG_20250106_085352_00_007sl.jpg', // 使用绝对路径
                    //     hotSpots: []
                    // }
                }
            }
        },
        computed: {
            // currentHotspots() {
            //     return this.hotspots[this.currentRoom] || [];
            // }
        },
        watch: {
            // currentRoom(newVal) {
            //     this.loadPanorama(newVal);
            // }
        },
        mounted() {
            // this.initViewer();
        },
        beforeUnmount() {
            if (this.viewer) {
                this.viewer.destroy();
            }
        },
        created() {
            EventBus.$on('set-scenes', (message) => {
                this.scenes=message.scenes;
                this.currentRoom=message.firstScene;
                this.initViewer();
            });
            EventBus.$on('set-scene-id', (message) => {
                this.currentRoom=message;
                this.loadPanorama(message);
            })
        },
        methods: {
            initViewer() {
                // 初始化所有场景的热点
                // Object.keys(this.scenes).forEach(roomId => {
                //     this.scenes[roomId].hotSpots = this.hotspots[roomId].map(hotspot => ({
                //         pitch: hotspot.position.pitch || 0,
                //         yaw: hotspot.position.yaw || 0,
                //         // type: 'info',
                //         // text: hotspot.text,
                //         cssClass: 'custom-hotspot',
                //         // id: hotspot.id
                //         type: 'custom',
                //         // clickHandlerArgs: hotspot,  // 关键修改
                //         // clickHandlerFunc: this.showHotspotInfo.bind(this, hotspot),
                //         // createTooltipArgs: { title: hotspot.title || hotspot.text }, // 关键修改
                //         // 热点创建时的DOM回调
                //         // createTooltipFunc: this.createCustomTooltip
                //     }));
                // });
                if (this.viewer) {
                    this.viewer.destroy();
                }
                this.viewer = window.pannellum.viewer(this.$refs.panoramaContainer, {
                    default: {
                        firstScene: this.currentRoom,
                        sceneFadeDuration: 1000,
                        autoLoad: true,  // 关键配置：自动加载
                        showControls: false,
                        mouseZoom: true,
                        autoRotate: 5,
                        autoRotateInactivityDelay: 5000,
                        compass: true,
                        preview: "http://111.229.223.177:8090/renren-admin/api/bg/getImage?name=IMG_20250106_085136_00_005sl.jpg",   // 禁用预览图
                        showFullscreenCtrl: false,
                        orientationOnByDefault: false,  // 默认禁用
                        showOrientationCtrl: false      // 隐藏方向控制按钮
                    },
                    scenes: this.scenes
                });
                // 添加热点事件监听
                this.$refs.panoramaContainer.addEventListener('mousemove', this.handleMouseMove);
            },

            loadPanorama(roomId) {
                if (!this.viewer) return;
                this.viewer.loadScene(roomId);
            },

            showTooltip(hotspot) {
                this.activeTooltip = hotspot;
            },

            hideTooltip() {
                this.activeTooltip = null;
            },

            handleMouseMove(e) {
                if (this.activeTooltip) {
                    this.tooltipPosition = {
                        left: `${e.clientX + 15}px`,
                        top: `${e.clientY + 15}px`
                    };
                }
            },

            // 添加双击事件处理
            handleDoubleClick(event) {
                if (!this.viewer) return;

                // 获取鼠标在容器内的相对位置
                const rect = this.$refs.panoramaContainer.getBoundingClientRect();
                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;

                // 转换为全景图坐标
                const viewer = this.viewer;
                const pitchYaw = viewer.mouseEventToCoords(event);

                this.clickPosition = {
                    x,
                    y,
                    yaw: pitchYaw[0],
                    pitch: pitchYaw[1]
                };

                // 3秒后自动隐藏坐标
                setTimeout(() => {
                    this.clickPosition = null;
                }, 3000);

                // 可以在这里添加自定义逻辑
                console.log('双击位置坐标:', this.clickPosition);

                // 如果需要添加标记点
                // this.addHotspot(this.clickPosition);
            },

            // 可选：添加标记点到双击位置
            addHotspot(position) {
                this.viewer.addHotSpot({
                    pitch: position.pitch,
                    yaw: position.yaw,
                    type: 'info',
                    text: `标记点 (${position.yaw.toFixed(1)}, ${position.pitch.toFixed(1)})`,
                    cssClass: 'custom-hotspot'
                });
            },

            // 自定义工具提示
            createCustomTooltip(hotSpotDiv, args) {
                try {
                    // 1. 参数安全检测
                    if (!hotSpotDiv || !args) {
                        console.warn('Invalid tooltip parameters');
                        return;
                    }

                    // 2. 获取显示文本（多级回退）
                    const tooltipText = args.title || args.text || '查看详情';

                    // 3. 创建DOM元素
                    const tooltip = document.createElement('div');
                    tooltip.className = 'custom-tooltip';
                    tooltip.innerHTML = `
                        <span>${this.escapeHtml(tooltipText)}</span>
                        ${args.icon ? `<i class="${args.icon}"></i>` : ''}
                      `;

                    // 4. 添加交互效果
                    tooltip.addEventListener('mouseenter', () => {
                        tooltip.style.opacity = '1';
                    });

                    tooltip.addEventListener('mouseleave', () => {
                        tooltip.style.opacity = '0';
                    });

                    hotSpotDiv.appendChild(tooltip);

                } catch (error) {
                    console.error('Failed to create tooltip:', error);
                }
            },
            // 辅助方法：防止XSS
            escapeHtml(unsafe) {
                return unsafe
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            },

            // 显示完整热点信息
            showHotspotInfo(hotspot) {
                this.activeHotspot = {
                    ...hotspot,
                    // 确保视频路径正确
                    video: hotspot.video ? require(`@/assets/videos/${hotspot.video}`) : null,
                    // 处理图片数组
                    images: hotspot.images ? hotspot.images.map(img => require(`@/assets/img/${img}`)) : null
                };
            },

            // 关闭弹窗
            closeModal() {
                this.activeHotspot = null;
            },

            // 打开图片灯箱
            openLightbox(index) {
                // 这里可以集成lightbox组件
                console.log('查看大图:', this.activeHotspot.images[index]);
            }
        }
    }
</script>

<style>
    .custom-tooltip span {
        position: absolute;
        white-space: nowrap;
        background: rgba(0,0,0,0.7);
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        top: -30px;
        left: 50%;
        transform: translateX(-50%);
        opacity: 0;
        transition: opacity 0.3s;
    }

    .enhanced-hotspot:hover .custom-tooltip span {
        opacity: 1;
    }

    /* 标记点弹窗样式 */
    .hotspot-modal {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.8);
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
        pointer-events: auto;
    }

    .modal-content {
        background: white;
        width: 80%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        padding: 20px;
        border-radius: 8px;
        position: relative;
    }

    .close-btn {
        position: absolute;
        top: 10px;
        right: 10px;
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
    }

    .hotspot-video {
        width: 100%;
        max-height: 400px;
        margin: 15px 0;
        background: #000;
    }

    .hotspot-description {
        margin: 15px 0;
        line-height: 1.6;
    }

    .image-gallery {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 10px;
        margin-top: 15px;
    }

    .image-gallery img {
        width: 100%;
        height: 80px;
        object-fit: cover;
        cursor: pointer;
        transition: transform 0.3s;
    }

    .image-gallery img:hover {
        transform: scale(1.05);
    }

    /* 添加坐标面板样式 */
    .position-panel {
        position: absolute;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 8px 16px;
        border-radius: 4px;
        z-index: 10;
        font-size: 14px;
    }

    /* 确保全景容器可接收鼠标事件 */
    #panorama-container {
        cursor: pointer;
    }

    /* 保持之前的样式不变 */
    #panorama-container {
        width: 100%;
        height: 100%;
    }

    .custom-hotspot {
        height: 20px;
        width: 20px;
        border-radius: 50%;
        background-color: rgba(255, 0, 0, 0.5);
        border: 2px solid white;
    }

    .custom-hotspot:hover {
        background-color: rgba(255, 0, 0, 0.8);
        transform: scale(1.3);
    }

    .tooltip {
        position: fixed;
        background-color: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 8px 12px;
        border-radius: 4px;
        font-size: 14px;
        max-width: 200px;
        z-index: 20;
        pointer-events: none;
    }

    .tooltip::after {
        content: '';
        position: absolute;
        top: -5px;
        left: 10px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 5px solid rgba(0, 0, 0, 0.8);
    }

    .pnlm-controls-container {
        background-color: rgba(0, 0, 0, 0.3) !important;
    }
</style>